package Reflect.Test;

import java.lang.reflect.Field;

/**
 * @author: zcw
 * @version: 1.0
 * 演示反射操作属性
 */
@SuppressWarnings ({"all"})
public class ReflectAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        //1. 得到Student类对应的 Class对象
        Class<?> stuClass = Class.forName ("Reflect.Test.Student");
        //2. 创建对象
        Object o = stuClass.newInstance ();
        System.out.println (o.getClass ());
        //3. 使用反射得到age属性对象
        Field age = stuClass.getField ("age");
        age.set (o,815);
        System.out.println (o);
        System.out.println (age.get (o));
        //4. 操作name属性
        Field name = stuClass.getDeclaredField ("name");
        //暴破
        name.setAccessible (true);
        name.set (null,"bc"); // 因为name是static，因此o可以写成null
//        name.set (o,"bc");
        System.out.println (name.get (null));
    }
}
class Student{
    public int age;
    private static String name;

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age + ",name=" + name +
                '}';
    }
}
